import User from '@/store/modules/user';
import { Dialog, Notify, Toast } from 'vant';

import request from '@/assets/js/request';
import util from '@/assets/js/public';
import { getToken } from '@/assets/js/auth';
import router from '../../router';

// PC 上项目的HTML文件名
const appHTML = {
    'A': 'html/apply/applicationForm.html',
    'B': 'html/apply/applicationDetailsForm.html',
    'C': 'html/apply/applicationBidForm.html',
    'D': 'html/apply/applicationSignedForm.html',
    'E': 'html/apply/applicationImplementForm.html',
    'F': 'html/apply/applicationImplementSupplierForm.html',
    'G': 'html/apply/applicationSignedOrderForm.html',
    'H': 'html/apply/applicationImplementPurchaseForm.html',
    'XZ': 'html/applyGather/applicationFormGather.html',
    'XC': 'html/applyEnhance/applicationFormSupport.html',
    'XB': 'html/applyEnhance/applicationFormSupport2.html',
    'XD': 'html/applyEnhance/applicationFormContract.html',
    'XE': 'html/applyEnhance/applicationFormDecision.html',
    'XEEF': 'html/applyEnhance/applicationFormDecision0206.html',
    'XF': 'html/applyEnhance/applicationFormDecisionMaking0906.html',
    'XFF': 'html/applyEnhance/applicationFormDecisionMaking.html',
    'XFFA': 'html/applyEnhance/applicationFormDecisionMakingOne.html',
    'XFFB': 'html/applyEnhance/applicationFormDecisionMakingOne.html',
    'XFFC': 'html/applyEnhance/applicationFormDecisionMakingOne0125.html',
    'XFFD': 'html/applyEnhance/applicationFormDecisionMakingOne0125.html',
    'XG': 'html/applyEnhance/applicationIntegratedForm.html',
    'XH': 'html/applyEnhance/applicationPartnerSelectionForm.html',
    'XI': 'html/applyEnhance/applicationEstablishmentForm.html',
    'XJ': 'html/applyEnhance/applicationFormOrderApproval.html',
    'XK': 'html/applyEnhance/applicationFormLoar.html',
    'XL': 'html/applyEnhance/applicationFormInformation.html',
    'XM': 'html/applyEnhance/applicationFormTaggingDetails.html',
    'XN': 'html/applyEnhance/applicationFormOpenTaggingDetails.html',
    'XO': 'html/applyEnhance/applicationFormContractBorrowFlow.html',
    'XP': 'html/applyEnhance/applicationFormSignConfirm.html',
    'XQ': 'html/applyEnhance/applicationFormSignConfirm.html',
    'XS': 'html/applyEnhance/applicationFormCertificateForm.html',
    'XT': 'html/applyEnhance/applicationFormCertificateReturnForm.html',
    'ZC': 'html/dictHQ/projectInformationDetails.html',
    'ZD': 'html/dictHQ/projectInformationDetails.html',
    'ZE': 'html/dictHQ/faultServiceForm.html',
    'ZF': 'html/dictHQ/projectInformationDetails.html',
    'ZG': 'html/dataRecovery/dataRecoveryApplication.html',
    'ZH': 'html/dataRecovery/dataRecoveryApplication.html',
    'ZI': 'html/dataRecovery/dataRecoveryApplication.html',
    'ZJ': 'html/auxiliary/esopBusinessToProjectDisclosureKexiang.html',
    'ZK': 'html/auxiliary/esopBusinessToProjectDisclosureKexiang.html',
    'ZL': 'html/auxiliary/esopBusinessToProjectDisclosureKexiang.html',
    'XU': 'html/applyEnhance/applicationFormApprovalProjectBack.html',
    'XV': 'html/auxiliary/applicationFormProjectContract.html',
    'XW': 'html/auxiliary/applicationFormProjectContract.html',
    'XX': 'html/auxiliary/applicationFormProjectContract.html',
    'XY': 'html/auxiliary/applicationFormProjectContract.html',
    'XVVI': 'html/auxiliary/esopToProjectContractParseIncome.html',
    'XWI': 'html/auxiliary/esopToProjectContractParseIncome.html',
    'XVVO': 'html/auxiliary/esopToProjectContractParseOutcome.html',
    'XWO': 'html/auxiliary/esopToProjectContractParseOutcome.html',
    'XVV': 'html/auxiliary/esopToProjectContractInfo.html',
    'XWW': 'html/auxiliary/esopToProjectContractInfo.html',
    'XXX': 'html/auxiliary/esopToProjectContractInfo.html',
    'XYY': 'html/auxiliary/esopToProjectContractInfo.html',
    'WA': 'html/maintain/workOrderManage.html',
    'WB': 'html/maintain/systemExceptionManage.html',
    'WC': 'html/maintain/optimizationManage.html',
    'WD': 'html/maintain/demandManage.html',
    'DA': 'html/dictHQ/contractToSendTenderKeXiang.html',
    'DB': 'html/dictHQ/contractToSendTenderKeXiang.html',
    'DC': 'html/dictHQ/contractToSendTenderKeXiang.html',
    'AA': 'html/dictHQ/initProjectAudit.html',
    'AB': 'html/dictHQ/initProjectAudit.html',
    'AC': 'html/dictHQ/initProjectAudit.html',
    'OA': 'html/dictHQ/initShutDownProcess.html',
    'OB': 'html/dictHQ/initShutDownProcess.html',
    'OC': 'html/dictHQ/initShutDownProcess.html',
    'OD': 'html/dictHQ/initRecoverProcess.html',
    'OE': 'html/dictHQ/initRecoverProcess.html',
    'OF': 'html/dictHQ/initRecoverProcess.html',
    'MA': 'html/qlcgt/esopBusinessToProjectDisclosureNewApp.html',
    'MB': 'html/qlcgt/esopBusinessToProjectDisclosureNewApp.html',
    'MC': 'html/qlcgt/esopBusinessToProjectDisclosureNewApp.html',
    'SA': 'html/qlcgt/initShutDownProcess.html',
    'SB': 'html/qlcgt/initShutDownProcess.html',
    'SC': 'html/qlcgt/initShutDownProcess.html',
    'SD': 'html/qlcgt/initRecoverProcess.html',
    'SE': 'html/qlcgt/initRecoverProcess.html',
    'SF': 'html/qlcgt/initRecoverProcess.html',
    'SG': 'html/qlcgt/initProjectStart.html',
    'SH': 'html/qlcgt/initProjectStart.html',
    'SI': 'html/qlcgt/initProjectStart.html',
    'SJ': 'html/qlcgt/initProjectProcess.html',
    'SK': 'html/qlcgt/initProjectProcess.html',
    'SL': 'html/qlcgt/initProjectProcess.html',
    'SM': 'html/qlcgt/initProjectJzjw.html',
    'SN': 'html/qlcgt/initProjectJzjw.html',
    'SO': 'html/qlcgt/initProjectJzjw.html',
    'TA': 'html/qlcgt/initProjectJzjw.html',
    'TAR': 'html/repair/repairProjectJzjw.html',
    'SP': 'html/qlcgt/initSalePreTeam.html',
    'SQ': 'html/qlcgt/initSalePreTeam.html',
    'SR': 'html/qlcgt/initSalePreTeam.html',
    'ST': 'html/qlcgt/initOnSaleTeam.html',
    'SU': 'html/qlcgt/initOnSaleTeam.html',
    'SV': 'html/qlcgt/initOnSaleTeam.html',
    'SW': 'html/qlcgt/postponeApplication0320.html',
    'SX': 'html/qlcgt/postponeApplication0320.html',
    'SY': 'html/qlcgt/postponeApplication0320.html',
    'MD': 'html/qlcgt/createDICTProjectDelNewApp.html',
    'ME': 'html/qlcgt/createDICTProjectDelNewApp.html',
    'MF': 'html/qlcgt/createDICTProjectDelNewApp.html',
    'MG': 'html/qlcgt/contractToSendTenderNewApp.html',
    'MH': 'html/qlcgt/contractToSendTenderNewApp.html',
    'MI': 'html/qlcgt/contractToSendTenderNewApp.html',
    'MJ': 'html/qlcgt/contractToPushServiceNewApp.html',
    'MK': 'html/qlcgt/contractToPushServiceNewApp.html',
    'ML': 'html/qlcgt/contractToPushServiceNewApp.html',
    'MM': 'html/qlcgt/projectMilestoneApp.html',
    'MN': 'html/qlcgt/projectMilestoneApp.html',
    'MO': 'html/qlcgt/projectMilestoneApp.html',
    'MP': 'html/qlcgt/oweWorth.html',
    'MQ': 'html/warZoneCompetition/warZoneApplication.html',
    'PA': 'html/partner/recruitPlanCreate.html',
    'PB': 'html/partner/recruitPlanCreate.html',
    'PC': 'html/partner/recruitAudit.html',
    'PD': 'html/partner/recruitAudit.html',
    'PE': 'html/partner/pick/pickPlanCreate.html',
    'PZ': 'html/partner/pick/pickPlanCreate.html',
    'PF': 'html/partner/pick/pickPlanCreate.html',
    'PG': 'html/partner/withdrawingApply.html',
    'PGI': 'html/partner/withdrawingApply.html',
    'PH': 'html/partner/withdrawingApply.html',
    'PI': 'html/partner/pick/pickReview.html',
    'PJ': 'html/partner/pick/pickReview.html',
    'PK': 'html/partner/pick/pickNegotiate.html',
    'PL': 'html/partner/pick/pickNegotiate.html',
    'PM': 'html/partner/resultPublicityAudit.html',
    'PN': 'html/partner/resultPublicityAudit.html',
    'PO': 'html/partner/pick/pickPublicityAudit.html',
    'PP': 'html/partner/pick/pickPublicityAudit.html',
    'PW': 'html/partner/pick/pickPublicityAudit.html',
    'PQ': 'html/partner/specialistExamine.html',
    'PR': 'html/partner/pick/pickSpecialistExamine.html',
    'PS': 'html/datum/siku/partnerProjectReview.html',
    'PSA': 'html/datum/siku/partnerProjectReview.html',
    'PSB': 'html/datum/siku/partnerProjectReview.html',
    'PSC': 'html/datum/siku/partnerProjectReview.html',
    'PSD': 'html/datum/siku/partnerProjectReviewAfter.html',
    'PSE': 'html/datum/siku/partnerProjectReviewAfter.html',
    'PSF': 'html/datum/siku/partnerProjectReviewAfter.html',
    'PT': 'html/partner/pick/pickPlanCreate.html',
    'PU': 'html/partner/pick/pickPublicityAudit.html',
    'PV': 'html/partner/pick/pickPublicityAudit.html',
    'YA': 'html/businessManage/businessInformationForm.html',
    'YB': 'html/businessManage/businessInformationForm.html',
    'YC': 'html/businessManage/businessChange.html',
    'YD': 'html/businessManage/businessChange.html',
    'YX': 'html/businessManage/clueInformationForm.html',
    'SJXY': 'html/applyEnhance/applicationBusinessResponseForm.html',
    'SQBF': 'html/applyEnhance/applicationBusinessVisitForm.html',
    'SRQR': 'html/auxiliary/applicationRevenueRecognitionForm.html',
    'SRQR2': 'html/auxiliary/applicationRevenueRecognitionForm1227.html',
    'SRQRZK': 'html/auxiliary/applicationRevenueRecognitionForm1227.html',
    'ZM': 'html/synergy/supportTaskApply.html',
    'ZN': 'html/synergy/supportTaskApply.html',
    'ZO': 'html/synergy/saleSupport.html',
    'ZP': 'html/synergy/saleSupport.html',
    'ZQ': 'html/synergy/distribute/taskDistribute.html',
    'ZR': 'html/synergy/general/generalTask.html',
    'ZS': 'html/synergy/general/generalTask.html',
    'ZT': 'html/synergy/general/generalTaskDistribute.html',
    'ZY': 'html/qlcgt/terminateAppLaunch.html',
    'ZZ': 'html/qlcgt/terminateAppLaunch.html',
    'MATRIX': 'html/applyEnhance/applicationContractApproveMatrix.html',
    'HT': 'html/qlcgt/projectContractApplication.html',
    'HTA': 'html/qlcgt/projectContractApplication.html',
    'HTB': 'html/qlcgt/projectContractApplication.html',
    'HTC': 'html/qlcgt/projectContractApplication.html',
    'BA': 'html/businessManage/businessInformationForm.html',
    'BB': 'html/businessManage/businessInformationForm.html',
    'BC': 'html/businessManage/businessInformationForm.html',
    'BD': 'html/businessManage/businessInformationSyncForm.html',
    'BE': 'html/businessManage/businessInformationSyncForm.html',
    'BF': 'html/businessManage/businessInformationSyncForm.html',
    'BG': 'html/businessManage/businessInformationForm.html',
    'BH': 'html/businessManage/businessInformationForm.html',
    'BI': 'html/businessManage/businessInformationForm.html',
    'BJ': 'html/businessManage/businessInformationSyncForm.html',
    'BK': 'html/businessManage/businessInformationSyncForm.html',
    'BL': 'html/businessManage/businessInformationSyncForm.html',
    'BM': 'html/businessManage/businessInformationForm.html',
    'BN': 'html/businessManage/businessInformationForm.html',
    'BO': 'html/businessManage/businessInformationSyncForm.html',
    'BP': 'html/businessManage/businessInformationSyncForm.html',
    'BQ': 'html/dictHQ/complaintFaultServiceForm.html',
    'BR': 'html/dictHQ/reminderFaultServiceForm.html',
    'BS': 'html/dictHQ/midOpinionFaultServiceForm.html',
    'SHTDA': 'html/qlcgt/initSaleAfterTeam.html',
    'SHTDB': 'html/qlcgt/initSaleAfterTeam.html',
    'SHTDC': 'html/qlcgt/initSaleAfterTeam.html',
    'GZBSC': 'html/dictHQ/faultServiceForm.html',
    'GZBSP': 'html/dictHQ/faultServiceForm.html',
    'ZCQC': 'html/dictHQ/faultServiceForm.html',
    'ZCQP': 'html/dictHQ/faultServiceForm.html',
    'YTHC': 'html/dictHQ/faultServiceForm.html',
    'YTHP': 'html/dictHQ/faultServiceForm.html',
    'PTC': 'html/datum/siku/partnerRecommendCity.html',
    'PBLB': 'html/datum/siku/partnerBlack.html',
    'PBLC': 'html/datum/siku/partnerBlack.html',
    'XJWH': 'html/patrolMaintenance/patrolMaintenanceForm.html',
    'QX': 'html/queryPermission/queryPermissionDetails.html',
    'QY': 'html/queryPermission/queryPermissionDetails.html',
    'AP': 'html/queryPermission/addQueryPermissionDetails.html',
    'WS': 'html/partner/warehousingForm.html',
    'WE': 'html/partner/warehousingForm.html',
    'EB': 'html/auxiliary/esopBusinessToProjectProcess.html',
    'EC': 'html/process/processBusinessClose.html',
    'APC': 'html/qlcgt/projectChangeDetails.html',
    'JX': 'html/inforCollection/projectCloseNormalForm.html',
    'JA': 'html/inforCollection/projectCloseForm.html',
    'JB': 'html/inforCollection/projectCloseForm.html',
    'JC': 'html/inforCollection/projectCloseForm.html',
    'GSZZ': 'html/datum/siku/sikuNaturalCompanyForm.html',
    'AL': 'html/datum/siku/sikuCaseForm.html',
    'TB': 'html/datum/siku/sikuTenderForm.html',
    'FA': 'html/datum/siku/sikuSchemeForm.html',
    'NA': 'html/expertDispatch/expertDispatchForm.html',
    'NB': 'html/expertDispatch/expertDispatchCloseForm.html',
    'NF': 'html/expertDispatch/expertDispatchCloseForm.html',
    'NC': 'html/expertDispatch/expertDispatchWithdrawForm.html',
    'ND': 'html/expertRecruitment/expertRecruitmentForm.html',
    'NE': 'html/expertRecruitment/expertRecruitmentSignUpForm.html',
    'HTBG': 'html/plan/applicationFormProjectIncomeUpdate.html',
    'ARZ': 'html/qlcgt/reconciliationApplyForm.html',
    'ARX': 'html/qlcgt/reconciliationApplyForm.html',
    'ARS': 'html/qlcgt/reconciliationApplyForm.html',
    'CPG': 'html/dictHQ/changeProjectGradeTable.html',
    'BT': 'html/sysProcessManagement/processLayout.html',
    'FGA': 'html/fiveGVertical/projectIdentifyForm.html',
    'FGB': 'html/fiveGVertical/projectIdentifyForm.html',
    'FGC': 'html/fiveGVertical/projectIdentifyForm.html',
    'UPC': 'html/datum/siku/partnerInfoChangeProcess.html',
    'UPD': 'html/datum/siku/partnerInfoChangeProcess.html',
    'SPD': 'html/dictboard/dueProjectApplicationForm.html',
    'YPL': 'html/applyEnhance/applicationFormBusinessJudged.html',
    'YPU': 'html/applyEnhance/applicationFormBusinessJudged.html',
    'HTTS': 'html/dictHQ/contractToPushServiceNewProcess.html'
}


// TODO: 起草流转前的风险评估（通用）
// 获取风险规则
function getSmartRemindConfigrationByProcessType(params) {
    let username = User.state.user.userName;
    return request(
        {
            url: process.env.VUE_APP_URL + '/action/openapi/bps/common/transmit/' +
                'smartRemindConfigration$api$getSmartRemindConfigrationByProcessType',
            contentType: 'application/json;charset=UTF-8',
            async: false,
            data: {
                'access_token': getToken(),
                'appCode': 'dict',
                'currentUserCode': util.encrypt(username),
                'versionName': '2.7.92',
                'kv': {
                    'currentUserCode': util.encrypt(username),
                    'source': 'MOBILE',
                    'htmlName': params.htmlName,
                    'businessId': params.businessId,
                },
            }
        }
    )
}

// 发送风险工单
function sendTaskTicketBySmartRemindConfigration(params) {
    let username = User.state.user.userName;
    return request(
        {
            url: process.env.VUE_APP_URL + '/action/openapi/bps/common/transmit/' +
                'smartRemindConfigration$api$sendTaskTicketBySmartRemindConfigration',
            contentType: 'application/json;charset=UTF-8',
            async: false,
            data: {
                'access_token': getToken(),
                'appCode': 'dict',
                'currentUserCode': util.encrypt(username),
                'versionName': '2.7.92',
                'kv': {
                    'currentUserCode': util.encrypt(username),
                    'source': 'MOBILE',
                    'htmlName': params.htmlName,
                    'businessId': params.businessId,
                    'id': params.id,
                    'pmInsId': params.pmInsId,
                },
                'jsonName': 'appDecision',
                'appDecision': {
                    'htmlName': params.htmlName,
                    'businessId': params.businessId,
                    'id': params.id,
                    'pmInsId': params.pmInsId,
                },
            }
        }
    )
}

// 定时获取风险处理状态
function getApplicationFormGatherByBusinessId(params) {
    let username = User.state.user.userName;
    return request(
        {
            url: process.env.VUE_APP_URL + '/action/openapi/bps/common/transmit/' +
                'applicationFormGather$api$getApplicationFormGatherByBusinessId',
            contentType: 'application/json;charset=UTF-8',
            async: false,
            data: {
                'access_token': getToken(),
                'appCode': 'dict',
                'currentUserCode': util.encrypt(username),
                'versionName': '2.7.92',
                'kv': {
                    'currentUserCode': util.encrypt(username),
                    'source': 'MOBILE',
                    'htmlName': params.htmlName,
                    'businessId': params.businessId,
                    'id': params.id,
                },
            }
        }
    )
}

// 过滤字符串中的非数字字符
function filterNumberString(str) {
    return str.replace(/[^.\d]/g, '');
}


var html_name = '';
var business_id = ''
var pmIns_id = ''

// 发起起草时的风险评估功能
export function controlRule(params, businessId, callback) {

    var location = params.location;
    if (location != 'dict.start' && location != 'dict.startToIndustryManagerProvince' && location != 'dict.startToCityAdmin' && location != 'dict.startToFirstAdmin') {
        callback()
        return false
    }

    var pmInsType = params.pmInsType;
    html_name = appHTML[pmInsType];
    business_id = businessId;
    pmIns_id = params.pmInsId ? params.pmInsId : '';

    // business_id = '371202311130012';
    // html_name = 'html/applyEnhance/applicationBusinessVisitForm.html'
    Toast.loading({ message: '风险校验中...', forbidClick: false });
    getSmartRemindConfigrationByProcessType({
        'htmlName': html_name,
        'businessId': business_id,
    }).then((result) => {
        Toast.clear();
        if (result.data.data) {
            controlRuleTwo(result.data.data, callback);
        }
        else
        {
            callback()
        }
    })
}



function controlRuleTwo(controlRule, callback) {

    var timer = null;
    var ruleLevel = {
        '低': [],
        '中': [],
        '高': [],
        '处理中': null
    }// 风险级别

    // 风险处理、分类
    controlRule.map(function (item) {

        if (item.rulerHandleResult == '审批通过') {
            var content = item.rulerName + ',风险管控工单已完成处理，审批已通过，风险已解除，可继续操作!';
            Dialog.alert({ title: '提示信息', message: content })
        }

        // 规则判断，存放规则结果
        var rule = [];
        item.ruleListModel.map(function (data) {

            // 界面上的值（填写、接口获取等）
            var formValue = document.querySelector('input[name="' + data.ruleFieldCode + '"]').value || '';

            // 日期取值优化处理（对比当天时间）
            try {
                if (data.ruleField.indexOf('日期') > -1) {
                    // 获取当前日期
                    var currentDate = new Date();
                    // 创建目标日期（2023-10-01）
                    var targetDate = new Date(formValue);
                    // 计算两个日期之间的差异（以毫秒为单位）
                    var dateDiff = currentDate - targetDate;
                    // 计算差异的天数
                    var daysDiff = Math.floor(dateDiff / (1000 * 60 * 60 * 24));
                    formValue = daysDiff;
                }
            } catch (e) {
            }

            if (data.ruleLogic.indexOf('不等于') > -1) rule.push(formValue != data.ruleValue);
            else if (data.ruleLogic.indexOf('等于') > -1) rule.push(formValue == data.ruleValue);
            else if (data.ruleLogic.indexOf('大于') > -1) rule.push(Number(filterNumberString(formValue)) > Number(filterNumberString(data.ruleValue)));
            else if (data.ruleLogic.indexOf('小于') > -1) rule.push(Number(filterNumberString(formValue)) < Number(filterNumberString(data.ruleValue)));
            else if (data.ruleLogic.indexOf('大于等于') > -1) rule.push(Number(filterNumberString(formValue)) >= Number(filterNumberString(data.ruleValue)));
            else if (data.ruleLogic.indexOf('小于等于') > -1) rule.push(Number(filterNumberString(formValue)) <= Number(filterNumberString(data.ruleValue)));
        })

        // 校验不通过添加配置 ,若页面上不存在该值校验通过
        if (eval(rule.join('&&'))) {

            if (!item.rulerHandleResult || item.rulerHandleResult == '审批不通过') {

                ruleLevel[item.rulerLevel].push({
                    id: item.id,
                    name: item.rulerName,
                    rulerHandleResult: item.rulerHandleResult
                });
            }
            else if (item.rulerHandleResult == '处理中') {

                ruleLevel['处理中'] = item
            }
        }
    })


    // 如果有正在处理的中风险直接提示
    if (ruleLevel['处理中']) {

        // 弹窗提示
        customTipsFun(ruleLevel['处理中'].rulerName)

        // 开启定时器，每10秒查询一次风险处理状态
        // 执行审批风险工单逻辑 第一个参数审批通过逻辑 第二个审批不通过逻辑
        timerFun(ruleLevel['处理中'], function () {

            // 弹窗提示成功（自动就会将之前的“等待弹窗”覆盖掉）
            Dialog.alert({
                title: '温馨提示', message: ruleLevel['处理中'].rulerName + '”风险审批通过！'
            }).then(() => {

                // 执行其他风险
                executeRule()
            });
        }, function () {

            // 弹窗提示失败（自动就会将之前的“等待弹窗”覆盖掉）
            Dialog.alert({
                title: '温馨提示', message: ruleLevel['处理中'].rulerName + '”风险审批不通过！'
            }).then(() => { });
        })
    }
    else {
        executeRule()
    }




    // 高、中、低风险依次处理逻辑
    function executeRule() {

        if (ruleLevel['高'].length > 0) {

            executeTall(0)
        }
        else {
            var mediumRisk = ruleLevel['中']
            var mediumIndex = 0;
            if (mediumRisk.length > 0) {

                function executeMedium() {
                    var logText;
                    if (mediumRisk[mediumIndex].rulerHandleResult == '审批不通过') {
                        logText = '您的风险防控工单未审批通过，已重新触发“' + mediumRisk[mediumIndex].name + '”风险，风险级别为中，请您确认是否继续，若您选择继续，系统将发送风险工单至地市风险管理员，风险管理员处理后您方可继续操作。';
                    } else {
                        logText = '您正在进行的操作已触发“' + mediumRisk[mediumIndex].name + '”风险，风险级别为中，请您确认是否继续，若您选择继续，系统将发送风险工单至地市风险管理员，风险管理员处理后您方可继续操作。';
                    }

                    Dialog.confirm({
                        title: '嵌入式风险管控', message: logText, confirmButtonText: '继续', cancelButtonText: '取消'
                    }).then(() => {

                        // 弹窗等待，只能退出或等待
                        customTipsFun(mediumRisk[mediumIndex].name)

                        // 发送风险工单
                        var id = mediumRisk[mediumIndex].id;
                        sendTaskTicketBySmartRemindConfigration({
                            'htmlName': html_name,
                            'businessId': business_id,
                            'pmInsId': pmIns_id,
                            'id': id,
                        }).then((result) => {

                        })

                        // 开启定时器，每10秒查询一次风险处理状态
                        // 执行审批风险工单逻辑 第一个参数审批通过逻辑 第二个审批不通过逻辑
                        timerFun(mediumRisk[mediumIndex], function () {

                            // 弹窗提示成功（自动就会将之前的“等待弹窗”覆盖掉）
                            Dialog.alert({
                                title: '温馨提示', message: mediumRisk[mediumIndex].name + '”风险审批通过！'
                            }).then(() => {

                                // 执行下一个中风险
                                if (mediumRisk[mediumIndex + 1]) {
                                    mediumIndex++;
                                    executeMedium()
                                } else {
                                    executeLow(0)
                                }
                            });
                        }, function () {
                            // 弹窗提示失败（自动就会将之前的“等待弹窗”覆盖掉）
                            Dialog.alert({
                                title: '温馨提示', message: mediumRisk[mediumIndex].name + '”风险审批不通过！'
                            }).then(() => { });
                        })
                    });
                }

                executeMedium();
            }
            else {
                executeLow(0)
            }
        }
    }

    // 高风险处理：一个个高风险弹窗提示 - 直接阻断操作
    function executeTall(index) {

        var tallRisk = ruleLevel['高']
        var logText = '您正在进行的操作已触发“' + tallRisk[index].name + '”风险，风险级别为高，按照管理要求，禁止该操作，请您按照要求进行整改。'
        Dialog.confirm({
            title: '嵌入式风险管控', message: logText, confirmButtonText: '继续', cancelButtonText: '取消'
        }).then(() => {

            if (tallRisk[index + 1]) {
                executeTall(index + 1)
            }
            else {
                return false
            }
        });
    };


    // 低风险处理：一个个低风险弹窗提示 - 直接通过
    function executeLow(index) {

        var lowRisk = ruleLevel['低']
        if (lowRisk.length > 0) {

            var logText = '您正在进行的操作已触发“' + lowRisk[index].name + '”风险，风险级别为“低”，按照管理要求流程挂起，请您按照要求进行整改'
            Dialog.confirm({
                title: '嵌入式风险管控', message: logText, confirmButtonText: '继续', cancelButtonText: '取消'
            }).then(() => {

                if (lowRisk[index + 1]) {
                    executeLow(index + 1)
                }
                else {
                    callback()
                }
            });
        }
        else {
            callback()
        }
    }



    // 审批中提示(中风险处理中专用)
    function customTipsFun(name, riskText) {

        if (!riskText) {
            riskText = '”风险正在审批中，请您耐心等待...';
        }

        var tips = '“' + name + '”' + riskText;
        Dialog.alert({
            title: '温馨提示', message: tips, confirmButtonText: '退出页面等待'
        }).then(() => {
            // 关闭Timer
            clearInterval(timer)

            // 返回上个页面
            window.history.length > 1 ? router.back() : router.push('/');
        });
    }

    // 开启计时器，每10秒查询一次风险处理状态
    function timerFun(mediumRisk, resCallback, errCallback) {

        timer = setInterval(function () {

            getApplicationFormGatherByBusinessId({
                'htmlName': html_name,
                'businessId': business_id,
                'pmInsId': pmIns_id,
                'id': mediumRisk.id,
            }).then((result) => {

                if (result.data.data == '审批通过') {
                    clearInterval(timer)
                    resCallback();
                } else if (result.data.data == '审批不通过') {
                    clearInterval(timer)
                    errCallback()
                }
            })
        }, 10000)
    }
}


